package cn.tedu.store.service.impl;

import cn.tedu.store.entity.User;
import cn.tedu.store.mapper.UserMapper;
import cn.tedu.store.service.IUserService;
import cn.tedu.store.service.ex.InsertException;
import cn.tedu.store.service.ex.PasswordNotMatchException;
import cn.tedu.store.service.ex.UserNotFoundException;
import cn.tedu.store.service.ex.UsernameDuplicateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


//@Serivce注解：SpringBoot项目环境加载时，会自动创建该类的一个对象
//交给Spring框架容器管理
@Service
public class UserServiceImpl  implements IUserService {
    @Autowired
    //从Spring框架容器中取出一个UserMapper实现类的对象，赋给下面的成员属性
    private UserMapper userMapper;

    /**
     * 注册接口实现
     * @param user 用户数据
     */
    public void reg(User user){
        //取出参数中的用户名
        String username = user.getUsername();
        //调用userMapper的findByUsername方法进行查询
        User result = userMapper.findByUsername(username);
        //如果查询结果不为null，抛出UsernameDuplicatException
        if (result!=null){
            throw new UsernameDuplicateException("注册失败，用户名已被占用！");
        }
        //调用userMapper的insert方法插入数据
        Integer rows = userMapper.insert(user);
        //如果受影响的行数不为1，抛出InsertException
        if (rows!=1){
            throw new InsertException("注册失败，未知插入异常，请联系管理员。");
        }
    }

    /**
     * 登录接口实现
     * @param username  用户名
     * @param password  密码
     * @return  登录用户信息
     */
    public User login(String username, String password) {
        //调用userMapper的findByUsername进行查询
        User result = userMapper.findByUsername(username);
        //若查询为null，抛UserNotFoundException
        if (result==null){
            throw new UserNotFoundException("非法用户名！");
        }
        //比较密码是否一致
        if (!result.getPassword().equals(password)){
            //若不一致，抛PassWordNotMatchException
            throw new PasswordNotMatchException("密码错误！");
        }
        //返回登录成功用户部分信息
        User user = new User();
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        return user;
    }

}
